export default {
  //获取已订阅的模板集合
  getSubscribeList (showModal = false, modalContent = '是否确认订阅消息提醒?') {
    uni.getSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log('settingData', res)

        let { mainSwitch, itemSettings } = res.subscriptionsSetting
        itemSettings = itemSettings ? itemSettings : {}
        const tmplIds = Object.keys(itemSettings)

        if (mainSwitch) {
          if (tmplIds.length > 0) {
            if (this.checkSubscribeStatus(itemSettings).isCloseMessage) {
              uni.openSetting({
                withSubscriptions: true
              })
            } else {
              // !showModal && this.subscribeMessage()
              if (showModal) {
                uni.showModal({
                  title: '提示',
                  content: modalContent,
                  success: (res) => {
                    if (res.confirm) {
                      this.subscribeMessage()
                    }
                  }
                })
              } else {
                this.subscribeMessage()
              }
            }
          } else {
            if (showModal) {
              uni.showModal({
                title: '提示',
                content: modalContent,
                success: (res) => {
                  if (res.confirm) {
                    this.subscribeMessage()
                  }
                }
              })
            } else {
              this.subscribeMessage()
            }
          }
        } else {
          uni.openSetting({
            withSubscriptions: true
          })
        }
      }
    })
  },
  //判断和记录模板订阅状态
  checkSubscribeStatus (itemSettings) {
    let isCloseMessage = false
    let templates = []

    for (const key in itemSettings) {
      if (key !== 'errMsg') {
        if (Object.hasOwnProperty.call(itemSettings, key)) {
          if (itemSettings[key] === 'reject') {
            isCloseMessage = true
          }

          let params = {
            templateId: key,
            isSubscribe: itemSettings[key] === 'accept' ? 1 : 0
          }

          templates.push(params)
        }
      }
    }

    return { isCloseMessage, templates }
  },
  //微信模板消息订阅
  subscribeMessage () {
    uni.requestSubscribeMessage({
      tmplIds: ['Og0POF6Y4bfbo7usClU6w7R99FT6ArWhzqE5Se-9BwM'],
      success: async (res) => {
        console.log('消息订阅操作', res)
        const { isCloseMessage, templates } = this.checkSubscribeStatus(res)
        // await setSubscribeMessage({
        //   memberId: this.data.memberId,
        //   templates,
        // })

        // uni.showToast({
        //   title: isCloseMessage ? '已取消订阅' : '订阅成功',
        //   icon: isCloseMessage ? 'error' : 'success'
        // })
      },
      fail (err) {
        console.log('订阅失败', err)
      }
    })
  }
}
